package com.easyexcell.easyexcellexample.utils.esayexcell.handler;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;

/**
 * 限定只能下拉框输入
 *
 * @User c.c
 * @Since 2023/9/1
 * @Time 17:29
 * @Description
 */

public class CustomSheetWriteHandler implements SheetWriteHandler {
  /**
   * v1 - v2 前两个值为几行到几行  v3 -v4 后两个值为几列到几列
   */
  private CellRangeAddressList cellRangeAddressList;
  /**
   * 下拉表的值
   */
  private String[] value;
  /**
   * 是否设置下拉选
   */
  private Boolean state;

  public CustomSheetWriteHandler(CellRangeAddressList cellRangeAddressList, String[] value, Boolean state) {
    this.cellRangeAddressList = cellRangeAddressList;
    this.value = value;
    this.state = state;
  }

  @Override
  public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {

  }

  /**
   * 定义下拉框
   */
  @Override
  public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    Sheet sheet = writeSheetHolder.getSheet();
    Workbook workbook = writeWorkbookHolder.getWorkbook();
    workbook.createCellStyle().setLocked(true);
    if (state) {
      DataValidationHelper helper = sheet.getDataValidationHelper();
      if (value.length == 0) {
//        throw new ServiceWarnException(BillExcelConstant.DROP_DOWN_ARRAY);
      }
      DataValidationConstraint constraint = helper.createExplicitListConstraint(value);
      // 指定行列约束
      DataValidation dataValidation = helper.createValidation(constraint, cellRangeAddressList);
      // 阻止输入非下拉选项的值
      dataValidation.setErrorStyle(DataValidation.ErrorStyle.STOP);
      dataValidation.setShowErrorBox(true);
      dataValidation.setSuppressDropDownArrow(true);
//      dataValidation.createErrorBox(BillExcelConstant.CREATE_ERROR_BOX_HINT, BillExcelConstant.CREATE_ERROR_BOX_INCONSISTENT);
      sheet.addValidationData(dataValidation);
    }
    // 目前不生效
    sheet.createFreezePane(0, 1, 0, 1);
    // 默认筛选条件
    sheet.setAutoFilter(CellRangeAddress.valueOf("1:1"));

  }

}
